using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Decav.Gatsb.Application;
using System.IO;
using Decav.Gatsb.Configuration;

namespace Decav.Gatsb.Web.Controls
{
    /// <summary>
    /// A control that holds an image that was created by a user.
    /// </summary>
    /// <remarks>
    /// Hides itself when the image does not exist.
    /// </remarks>
    public class UserImage : HtmlImage
    {
        public UserImage()
        {
        }

        /// <summary>
        /// Gets or sets the size of the image.
        /// </summary>
        public UserImageSize Size
        {
            get
            {
                if (ViewState["Size"] == null)
                    return UserImageSize.Original;

                return (UserImageSize)ViewState["Size"];
            }
            set
            {
                ViewState["Size"] = value;
                UpdateImageUrl();
            }
        }

        /// <summary>
        /// Gets or sets the unique identifier of the image.
        /// </summary>
        public Guid ImageId
        {
            get
            {
                if (ViewState["ImageId"] == null)
                    return Guid.Empty;

                return (Guid)ViewState["ImageId"];
            }
            set
            {
                ViewState["ImageId"] = value;
                UpdateImageUrl();
            }
        }

        /// <summary>
        /// Gets whether or not the specified image exists and can be shown.
        /// </summary>
        public bool ImageExists
        {
            get
            {
                return ImageId != Guid.Empty && File.Exists(Path.Combine(GatsbConfigurationSection.Current.UserUploadedImagesFolder, ImageId.ToString()));
            }
        }

        private void UpdateImageUrl()
        {
            this.Visible = ImageExists;
            this.Src = GatsbApplication.Current.GetImageUrl(ImageId, Size);
        }

        protected override void OnPreRender(EventArgs e)
        {
            UpdateImageUrl();
            base.OnPreRender(e);
        }
    }
}
